package com.yellowpage.ndc.action;
  
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.yellowpage.white.common.Configuration;
import com.yellowpage.white.common.Constants;
import com.yellowpage.white.struts.BaseAction;
import com.yellowpage.white.struts.Module;
import com.yellowpage.white.struts.OperationType;
import com.yellowpage.white.util.Util4Java;
import com.yellowpage.ndc.data.ManageRegion;
import com.yellowpage.ndc.service.ManageRegionService;

public class ManageRegionAction extends BaseAction {

    public String RESULT_QUERY = "query";
    public String RESULT_ADD = "add";
	public String RESULT_EDIT = "edit";
	public String RESULT_QUERY_SEL = "querySel";
	public String RESULT_QUERY_SEL_TREE = "querySelTree";
	
	private Configuration configuration;
	
	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}
	
	private List<ManageRegion> manageRegionList = new ArrayList<ManageRegion>();
	private List<Map> resultList = new ArrayList<Map>();
	
	private ManageRegion manageRegion;
	private ManageRegionService manageRegionService;
	
	private String selectedId;	
	private String[] selectedIds;	
	private String message;
	private String manageRegionStr;
		private String query_regionCode;
		private String query_shortName;
		private String query_engName;
		private String query_telLength;
		private String query_areaCode;
		private String query_abbrName;
		private String query_note;
		private String query_name;
		private String query_code;
		private String register_name;
		
	public void prepare() {
		super.prepare();
	
		if (this.selectedId != null && !this.selectedId.equals("")) {
			this.manageRegion = manageRegionService.getManageRegion(Long.parseLong(selectedId));
		}
	}
	
	public String queryByPage() {		
		initPageRender();
		
		Map queryMap = new HashMap();	
			    queryMap.put("regionCode", query_regionCode);
	    	    queryMap.put("shortName", query_shortName);
	    	    queryMap.put("engName", query_engName);
	    	    queryMap.put("telLength", query_telLength);
	    	    queryMap.put("areaCode", query_areaCode);
	    	    queryMap.put("abbrName", query_abbrName);
	    	    queryMap.put("note", query_note);
	    	    queryMap.put("name", query_name);
	    	    	
		resultList = manageRegionService.queryManageRegionByPage(queryMap, pageRender);
		
		setPageRenderToRequest();

		return RESULT_QUERY;
	}
	
	public String querySelByPage() {
		log.error("querySelByPage in....................");
		initPageRender();

		Map queryMap = new HashMap();
		queryMap.put("regionCode", query_regionCode);
		resultList = manageRegionService.queryManageRegionByPage(queryMap, pageRender);

		setPageRenderToRequest();

		return RESULT_QUERY_SEL;
	}
	public String querySelByPageTree() {
		
		Map queryMap = new HashMap();
		queryMap.put("regionCode", query_regionCode);
		resultList = manageRegionService.getManageRegionTree(queryMap);
		
		manageRegionStr = "";
		if(resultList.size()>0){
			for (Map map : resultList) {
				if(map.get("code").equals("000000")){
					manageRegionStr +="d.add(1,0,'<input type=radio name=selectedIds value="+map.get("code")+" style=line-height:-2 id=selectedIds_"+map.get("code")+">"+map.get("code")+"&nbsp;"+map.get("name")+"');";
				}else{
					manageRegionStr +="d.add("+map.get("code")+",0,'<input type=radio name=selectedIds value="+map.get("code")+" style=line-height:-2 id=selectedIds_"+map.get("code")+">"+map.get("code")+"&nbsp;"+map.get("name")+"');";
				}
				List<Map> cityList = (List<Map>) map.get("city");
				if(cityList!=null){
					for (Map city : cityList) {
						manageRegionStr +="d.add("+city.get("code")+","+map.get("code")+",'<input type=radio name=selectedIds value="+city.get("code")+" style=line-height:-2 id=selectedIds_"+city.get("code")+">"+city.get("code")+"&nbsp;"+city.get("name")+"');";
						List<Map> districtList = (List<Map>) city.get("district");
						if(districtList!=null){
							for (Map district : districtList) {
								manageRegionStr +="d.add("+district.get("code")+","+city.get("code")+",'<input type=radio name=selectedIds value="+district.get("code")+" style=line-height:-2 id=selectedIds_"+district.get("code")+">"+district.get("code")+"&nbsp;"+district.get("name")+"');";
							}
						}	
						
					}
				}
			}
		}
		return RESULT_QUERY_SEL_TREE;
	}
	
	public void getNameByCode() throws IOException{
		HttpServletResponse response = ServletActionContext.getResponse(); 
		response.setContentType("text/xml; charset=utf-8");
		response.setCharacterEncoding("utf-8");
	    PrintWriter out = response.getWriter();
	    register_name=manageRegionService.getCodeName(query_code);
	    try {
	    	if(register_name != null){
	    		out.print(register_name);
	    	}else{
	    		out.print("");
	    	}
	    	
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			out.print("");
		}
		out.flush();
		out.close();
	}
	
	public void exportExcel() {		
		Map queryMap = new HashMap();	
			    queryMap.put("regionCode", query_regionCode);
	    	    queryMap.put("shortName", query_shortName);
	    	    queryMap.put("engName", query_engName);
	    	    queryMap.put("telLength", query_telLength);
	    	    queryMap.put("areaCode", query_areaCode);
	    	    queryMap.put("abbrName", query_abbrName);
	    	    queryMap.put("note", query_note);
	    	    queryMap.put("name", query_name);
	    	    	
		resultList = manageRegionService.queryManageRegionByPage(queryMap, pageRender);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/x-download");
		OutputStream outp = null;		
		response.addHeader("Content-Disposition", "attachment;filename="
				+ "ManageRegion.xls");
		try {
			outp = response.getOutputStream();
			
			
			HSSFWorkbook workbook = new HSSFWorkbook();
			
			HSSFSheet sheet = workbook.createSheet("ProdGroup");	
			HSSFRow row = sheet.createRow(0);		
			sheet.autoSizeColumn((short)0); 
			row.createCell(0).setCellValue("REGION_CODE ");	
			row.createCell(1).setCellValue("SHORT_NAME ");
			row.createCell(2).setCellValue("ENG_NAME ");
			row.createCell(3).setCellValue("TEL_LENGTH ");
			row.createCell(4).setCellValue("AREA_CODE ");
			row.createCell(5).setCellValue("ABBR_NAME ");
			row.createCell(6).setCellValue("NOTE ");
			row.createCell(7).setCellValue("NAME ");
			
			
			
			for (int i = 0; i < resultList.size(); i++) {
			
				HSSFRow data_row = sheet.createRow(i+1);			
			   Map result = (Map)resultList.get(i);	 		 
				data_row.createCell(0).setCellValue(result.get("REGION_CODE")!=null?result.get("REGION_CODE").toString():"");					
				data_row.createCell(1).setCellValue(result.get("SHORT_NAME")!=null?result.get("SHORT_NAME").toString():"");
				data_row.createCell(2).setCellValue(result.get("ENG_NAME")!=null?result.get("ENG_NAME").toString():"");
				data_row.createCell(3).setCellValue(result.get("TEL_LENGTH")!=null?result.get("TEL_LENGTH").toString():"");
				data_row.createCell(4).setCellValue(result.get("AREA_CODE")!=null?result.get("AREA_CODE").toString():"");
				data_row.createCell(5).setCellValue(result.get("ABBR_NAME")!=null?result.get("ABBR_NAME").toString():"");
				data_row.createCell(6).setCellValue(result.get("NOTE")!=null?result.get("NOTE").toString():"");
				data_row.createCell(7).setCellValue(result.get("NAME")!=null?result.get("NAME").toString():"");
				}					
			workbook.write(outp);			
				response.flushBuffer();
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				this.addActionError("** 生成文件错误 !");
			} finally {
				if (outp != null) {
					try {
						outp.close();
					} catch (IOException e) {
						log.error(e.getMessage(), e);
					}
				}
			}		
		}	
	public void exportCsv() {		
		Map queryMap = new HashMap();	
			    queryMap.put("regionCode", query_regionCode);
	    	    queryMap.put("shortName", query_shortName);
	    	    queryMap.put("engName", query_engName);
	    	    queryMap.put("telLength", query_telLength);
	    	    queryMap.put("areaCode", query_areaCode);
	    	    queryMap.put("abbrName", query_abbrName);
	    	    queryMap.put("note", query_note);
	    	    queryMap.put("name", query_name);
	    	    	
		resultList = manageRegionService.queryManageRegionByPage(queryMap, pageRender);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/x-download");
		OutputStream outp = null;		
		response.addHeader("Content-Disposition", "attachment;filename="
				+ "ManageRegion.csv");
		try {
			outp = response.getOutputStream();
			
			
			HSSFWorkbook workbook = new HSSFWorkbook();
			
			HSSFSheet sheet = workbook.createSheet("ProdGroup");	
			HSSFRow row = sheet.createRow(0);		
			sheet.autoSizeColumn((short)0); 
			row.createCell(0).setCellValue("REGION_CODE ");	
			row.createCell(1).setCellValue("SHORT_NAME ");
			row.createCell(2).setCellValue("ENG_NAME ");
			row.createCell(3).setCellValue("TEL_LENGTH ");
			row.createCell(4).setCellValue("AREA_CODE ");
			row.createCell(5).setCellValue("ABBR_NAME ");
			row.createCell(6).setCellValue("NOTE ");
			row.createCell(7).setCellValue("NAME ");
			
			
			
			for (int i = 0; i < resultList.size(); i++) {
			
				HSSFRow data_row = sheet.createRow(i+1);			
			   Map result = (Map)resultList.get(i);	 		 
				data_row.createCell(0).setCellValue(result.get("REGION_CODE")!=null?result.get("REGION_CODE").toString():"");					
				data_row.createCell(1).setCellValue(result.get("SHORT_NAME")!=null?result.get("SHORT_NAME").toString():"");
				data_row.createCell(2).setCellValue(result.get("ENG_NAME")!=null?result.get("ENG_NAME").toString():"");
				data_row.createCell(3).setCellValue(result.get("TEL_LENGTH")!=null?result.get("TEL_LENGTH").toString():"");
				data_row.createCell(4).setCellValue(result.get("AREA_CODE")!=null?result.get("AREA_CODE").toString():"");
				data_row.createCell(5).setCellValue(result.get("ABBR_NAME")!=null?result.get("ABBR_NAME").toString():"");
				data_row.createCell(6).setCellValue(result.get("NOTE")!=null?result.get("NOTE").toString():"");
				data_row.createCell(7).setCellValue(result.get("NAME")!=null?result.get("NAME").toString():"");
				}					
			workbook.write(outp);			
				response.flushBuffer();
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				this.addActionError("** 生成文件错误 !");
			} finally {
				if (outp != null) {
					try {
						outp.close();
					} catch (IOException e) {
						log.error(e.getMessage(), e);
					}
				}
			}		
		}
	
	public String toAdd() {
		return RESULT_ADD;
	}
	
	public String save() {
	    
		manageRegionService.saveManageRegion(manageRegion);		
		
		message = "新增成功!";
		return RESULT_ADD;
	}
	
	public void validateSave() {
	    	    	    if (manageRegion.getRegionCode().length() == 0) {
			this.addActionError("** RegionCode 不能为空 !");
		}
			    	    	    if (manageRegion.getShortName().length() == 0) {
			this.addActionError("** ShortName 不能为空 !");
		}
			    	    	    if (manageRegion.getEngName().length() == 0) {
			this.addActionError("** EngName 不能为空 !");
		}
			    	    	    	    	    if (manageRegion.getAreaCode().length() == 0) {
			this.addActionError("** AreaCode 不能为空 !");
		}
			    	    	    if (manageRegion.getAbbrName().length() == 0) {
			this.addActionError("** AbbrName 不能为空 !");
		}
			    	    	    if (manageRegion.getNote().length() == 0) {
			this.addActionError("** Note 不能为空 !");
		}
			    	    	    if (manageRegion.getName().length() == 0) {
			this.addActionError("** Name 不能为空 !");
		}
			    	    
		this.setValidatorResult("/ndc/ManageRegionAdd.jsp");		
	}
	
	public String toEdit() {
	    Long id = new Long(selectedId);
	    
	    manageRegion = manageRegionService.getManageRegion(id);
	
		return RESULT_EDIT;
	}
	
	public String update() {
	
	    manageRegionService.updateManageRegion(manageRegion);	

		message = "修改成功!";
	    
		return RESULT_EDIT;
	}
	
	public void validateUpdate() {
					    if (manageRegion.getRegionCode().length() == 0) {
			this.addActionError("** RegionCode 不能为空 !");
		}
			    			    if (manageRegion.getShortName().length() == 0) {
			this.addActionError("** ShortName 不能为空 !");
		}
			    			    if (manageRegion.getEngName().length() == 0) {
			this.addActionError("** EngName 不能为空 !");
		}
			    			    			    if (manageRegion.getAreaCode().length() == 0) {
			this.addActionError("** AreaCode 不能为空 !");
		}
			    			    if (manageRegion.getAbbrName().length() == 0) {
			this.addActionError("** AbbrName 不能为空 !");
		}
			    			    if (manageRegion.getNote().length() == 0) {
			this.addActionError("** Note 不能为空 !");
		}
			    			    if (manageRegion.getName().length() == 0) {
			this.addActionError("** Name 不能为空 !");
		}
			    		this.setValidatorResult("/ndc/ManageRegionUpdate.jsp");	
	}
	
	public String delete() {	    
	    List ids = new ArrayList();
	    
		for(String id : selectedIds){
			ids.add(Long.valueOf(id));
		}
		
		try {
			this.manageRegionService.delete(ids);
		} catch (Exception e) {
			System.out.println("异常....");
			this.addActionError("** 可能含有子记录约束冲�?删除失败 !");
		}
		
		
		return queryByPage();
	}	
	
	

	/**
	 * getters and setters
	 * 
	 * @return
	 */
	 public void setManageRegion(ManageRegion manageRegion) {
		this.manageRegion = manageRegion;
	}
	
	public ManageRegion getManageRegion() {
		return manageRegion;
	}
	 
	 
	 public void setManageRegionService(ManageRegionService manageRegionService) {
		this.manageRegionService = manageRegionService;
	}
	
	public List<ManageRegion> getManageRegionList() {
		return manageRegionList;
	}

	public void setManageRegionList(List<ManageRegion> manageRegionList) {
		this.manageRegionList = manageRegionList;
	}
	
	public String getSelectedId() {
		return selectedId;
	}

	public void setSelectedId(String selectedId) {
		this.selectedId = selectedId;
	}

	public String[] getSelectedIds() {
		return selectedIds;
	}

	public void setSelectedIds(String[] selectedIds) {
		this.selectedIds = selectedIds;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	public List<Map> getResultList() {
		return resultList;
	}

	public void setResultList(List<Map> resultList) {
		this.resultList = resultList;
	}
	
	    public String getQuery_regionCode() {
        return this.query_regionCode;
    }
    
    public void setQuery_regionCode(String regionCode){
        this.query_regionCode = regionCode;
    }    

        public String getQuery_shortName() {
        return this.query_shortName;
    }
    
    public void setQuery_shortName(String shortName){
        this.query_shortName = shortName;
    }    

        public String getQuery_engName() {
        return this.query_engName;
    }
    
    public void setQuery_engName(String engName){
        this.query_engName = engName;
    }    

        public String getQuery_telLength() {
        return this.query_telLength;
    }
    
    public void setQuery_telLength(String telLength){
        this.query_telLength = telLength;
    }    

        public String getQuery_areaCode() {
        return this.query_areaCode;
    }
    
    public void setQuery_areaCode(String areaCode){
        this.query_areaCode = areaCode;
    }    

        public String getQuery_abbrName() {
        return this.query_abbrName;
    }
    
    public void setQuery_abbrName(String abbrName){
        this.query_abbrName = abbrName;
    }    

        public String getQuery_note() {
        return this.query_note;
    }
    
    public void setQuery_note(String note){
        this.query_note = note;
    }    

        public String getQuery_name() {
        return this.query_name;
    }
    
    public void setQuery_name(String name){
        this.query_name = name;
    }

	public String getQuery_code() {
		return query_code;
	}

	public void setQuery_code(String query_code) {
		this.query_code = query_code;
	}

	public String getRegister_name() {
		return register_name;
	}

	public void setRegister_name(String register_name) {
		this.register_name = register_name;
	}

	public String getManageRegionStr() {
		return manageRegionStr;
	}

	public void setManageRegionStr(String manageRegionStr) {
		this.manageRegionStr = manageRegionStr;
	}

	public ManageRegionService getManageRegionService() {
		return manageRegionService;
	}    

    
	
}
